<template>
  <div class="page-container">
    <!-- 下拉刷新容器 -->
    <div class="pull-refresh" ref="pullRefresh" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
      @touchend="handleTouchEnd">
      <div class="refresh-indicator" :style="refreshIndicatorStyle">
        <svg v-if="isRefreshing" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
          fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
          class="loading-icon">
          <path d="M23 4v6h-6"></path>
          <path d="M1 20v-6h6"></path>
          <path d="m3.51 9 9.08 9.09L21 12"></path>
        </svg>
        <span v-else-if="pullDistance > 50">释放刷新</span>
        <span v-else>下拉刷新</span>
      </div>

      <!-- 电影网格列表 -->
      <div class="movie-grid">
        <MovieCard v-for="movie in movies" :key="movie.id" :id="movie.id" :title="movie.title"
          :posterUrl="movie.posterUrl" :genre="movie.genre" :rating="movie.rating" :description="movie.description"
          @click="handleCardClick(movie.id)" />
      </div>

      <!-- 上拉加载提示 -->
      <div v-if="isLoadingMore" class="loading-more">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="loading-icon">
          <path d="M23 4v6h-6"></path>
          <path d="M1 20v-6h6"></path>
          <path d="m3.51 9 9.08 9.09L21 12"></path>
        </svg>
        加载中...
      </div>
      <div v-if="!hasMore && !isLoadingMore" class="no-more">没有更多内容了</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import MovieCard from '@/components/MovieCard.vue';
import type { Movies } from '@/dataType/movieType';
import { movieService } from '@/services/movieService';
import { useRouter } from 'vue-router'
import { useMovieTypeStore } from '@/stores/movie'

//全局状态
const movieTypeStore = useMovieTypeStore();


//路由管理
const router = useRouter()
// 状态管理
const movies = ref<Movies[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const isLoadingMore = ref(false);
const isRefreshing = ref(false);
// 路由参数
watch(() => router.currentRoute.value.params.type, (newType) => {
  currentPage.value = 1;
  movies.value = [];
  movieTypeStore.setType(newType as string);
  loadMovies(currentPage.value);
})

// 下拉刷新相关变量
const pullRefresh = ref<HTMLDivElement | null>(null);
const startY = ref(0);
const pullDistance = ref(0);
const isPulling = ref(false);
const refreshThreshold = 50; // 触发刷新的最小下拉距离


// 加载电影数据
const loadMovies = async (page: number, isRefresh = false) => {
  if (isRefresh) {
    isRefreshing.value = true;
  } else {
    isLoadingMore.value = true;
  }

  try {
    // 模拟API请求延迟
    await movieService.getMovies(page, pageSize.value, movieTypeStore.type).then(res => {
      if (isRefresh) {
        movies.value = res.records;
      } else {
        movies.value = [...movies.value, ...res.records];
      }
      hasMore.value = page * pageSize.value < res.total;
    })
  } catch (error) {
    console.error('加载电影数据失败:', error);
  } finally {
    isRefreshing.value = false;
    isLoadingMore.value = false;
    isPulling.value = false;
    pullDistance.value = 0;
  }
};

// 上拉加载更多
const loadMoreMovies = () => {
  if (!isLoadingMore.value && !isRefreshing.value && hasMore.value) {
    currentPage.value++;
    loadMovies(currentPage.value);
  }
};

// 下拉刷新数据
const refreshMovies = () => {
  currentPage.value = 1;
  loadMovies(currentPage.value, true);
};

// 处理触摸开始
const handleTouchStart = (e: TouchEvent) => {
  if (isRefreshing.value || isLoadingMore.value) return;
  // 只有在顶部时才允许下拉刷新
  if ((pullRefresh.value?.scrollTop || 0) <= 0) {
    startY.value = e.touches[0].clientY;
    isPulling.value = true;
  }
};

// 处理触摸移动
const handleTouchMove = (e: TouchEvent) => {
  if (!isPulling.value || isRefreshing.value) return;
  const currentY = e.touches[0].clientY;
  const distance = currentY - startY.value;

  if (distance > 0) {
    e.preventDefault(); // 阻止默认滚动行为
    pullDistance.value = Math.min(distance, refreshThreshold + 20); // 限制最大下拉距离
  }
};

// 处理触摸结束
const handleTouchEnd = () => {
  if (!isPulling.value || isRefreshing.value) return;

  if (pullDistance.value >= refreshThreshold) {
    refreshMovies(); // 触发刷新
  } else {
    // 未达到阈值，重置状态
    pullDistance.value = 0;
    isPulling.value = false;
  }
};

// 监听滚动事件（上拉加载）
const handleScroll = () => {
  if (!pullRefresh.value || isLoadingMore.value || isRefreshing.value || !hasMore.value) return;

  const { scrollTop, scrollHeight, clientHeight } = pullRefresh.value;
  // 滚动到底部附近时加载更多
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    loadMoreMovies();
  }
};

// 卡片点击事件
const handleCardClick = (id: number) => {
  console.log(`点击了电影卡片: ${id}`);
  // 可以添加路由跳转或详情展示逻辑
  router.push({
    path: `/movie/details/${id}`,
  })
};

// 计算刷新指示器样式
const refreshIndicatorStyle = ref<Record<string, string>>({
  transition: 'transform 0.3s ease',
  transform: 'translateY(-100%)'
});

// 监听下拉距离变化，更新指示器样式
watch(pullDistance, (newVal) => {
  if (isRefreshing.value) {
    refreshIndicatorStyle.value.transform = 'translateY(0)';
  } else if (isPulling.value) {
    refreshIndicatorStyle.value.transform = `translateY(${newVal}px)`;
  } else {
    refreshIndicatorStyle.value.transform = 'translateY(-100%)';
  }
});

// 初始化
onMounted(() => {
  loadMovies(currentPage.value);
  pullRefresh.value?.addEventListener('scroll', handleScroll);
});

// 清理事件监听
onUnmounted(() => {
  pullRefresh.value?.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.page-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.pull-refresh {
  height: 100vh;
  overflow-y: auto;
  position: relative;
}

.refresh-indicator {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  transform: translateY(-100%);
}

.loading-icon {
  animation: spin 1.5s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.movie-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 24px;
  padding: 20px;
}

.loading-more {
  text-align: center;
  padding: 20px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-more {
  text-align: center;
  padding: 20px;
  color: #666;
}

@media (max-width: 768px) {
  .movie-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 16px;
    padding: 15px;
  }
}

/* 隐藏滚动条但保留滚动功能 */
.pull-refresh::-webkit-scrollbar {
  display: none;
}

.pull-refresh {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
</style>